<template>
  <ele-page flex-table>
    <ComHeader :title="isUpdate ? `编辑要货单[${info.order_sn}]` : '新增要货单'" @back="goBack()" />
    <ele-bottom-bar :teleported="true">
      <template #extra>
        <!-- <el-button type="" :loading="loading" @click="save('DR')">草稿</el-button> -->
        <el-button type="" @click="goBack()">返回</el-button>
        <el-divider direction="vertical" />
        <el-button type="primary" :loading="loading" @click="save()">保存</el-button>
      </template>
    </ele-bottom-bar>

    <el-scrollbar>
      <div flex-table>
        <el-form ref="formRef" label-suffix="" class="overflow-hidden" :model="form" :rules="rules" label-width="auto">
          <ele-card :body-style="{ paddingBottom: '5px' }" class="mb-10px!">
            <el-row :gutter="20">
              <el-col :lg="5" :md="8" :sm="12">
                <el-form-item label="单据日期" prop="order_date">
                  <el-date-picker
                    v-model="form.order_date"
                    value-format="YYYY-MM-DD"
                    type="date"
                    placeholder="请选择单据日期"
                    class="w-full!"
                  />
                </el-form-item>
              </el-col>

              <el-col :md="5" :sm="8" :xs="12">
                <el-form-item label="货主" prop="supplier_id">
                  <el-select
                    v-model="form.supplier_id"
                    placeholder="请选择货主"
                    clearable
                    :disabled="isUpdate"
                  >
                    <el-option v-for="item in supplierList" :key="item.id" :value="item.id" :label="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :md="5" :sm="8" :xs="12">
                <el-form-item label="开放平台" prop="su_id">
                  <el-select v-model="form.su_id" :disabled="!form.supplier_id || isUpdate" placeholder="请选择开放平台" clearable @change="suChange">
                    <el-option v-for="item in suList" :key="item.id" :value="item.id" :label="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :md="9" :sm="12" :xs="12">
                <el-form-item label="订单备注" prop="remark">
                  <el-input v-model="form.remark" clearable placeholder="请填写备注" />
                </el-form-item>
              </el-col>

              <el-col :md="5" :sm="8" :xs="12">
                <el-form-item label="收货人" prop="contacts">
                  <el-input v-model="form.contacts" clearable placeholder="请填写收货人" />
                </el-form-item>
              </el-col>

              <el-col :md="5" :sm="8" :xs="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="form.phone" clearable placeholder="请填写联系电话" />
                </el-form-item>
              </el-col>
              <el-col :md="9" :sm="12" :xs="12">
                <el-form-item label="联系地址" prop="address">
                  <el-input v-model="form.address" clearable placeholder="请填写联系地址" />
                </el-form-item>
              </el-col>
            </el-row>
          </ele-card>
          <ele-card :body-style="{ paddingBottom: '5px' }">
            <el-form-item label="商品信息" label-position="top" label-width="200px" prop="product">
              <template #label>
                <span class="flex-inline items-center">
                  <div class="">商品信息</div>
                  <div class="ml-12px">
                    <el-button
                      type="primary"
                      icon="IconElPlus"
                      :disabled="!form.supplier_id"
                      plain
                      @click="showProduct = true"
                    >
                      新增商品
                    </el-button>
                  </div>
                </span>
              </template>
              <el-table
                ref="tableRef"
                :data="form.product"
                size=""
                border
                style="width: 100%"
                show-summary
                :summary-method="getSummaries"
              >
                <el-table-column type="index" label="序" width="60" align="center" />
                <el-table-column prop="product_name" label="商品名称" align="left" min-width="130" />
                <el-table-column prop="product_code" label="商品编码" align="center" />
                <el-table-column prop="unit" label="主单位" align="center" />
                <el-table-column v-if="isUpdate" prop="need_num" label="要货数量" align="center" />
                <el-table-column
                  prop="warehouse"
                  label="配货数量"
                  align="center"
                  :min-width="300"
                >
                  <template #default="{ row, $index }">
                    <div v-for="(wg, g) in row.warehouse" :key="g" class="flex-a" :class="g ? 'mt-7px' : ''">
                      <el-scrollbar class="flex-1">
                        <div class="flex-a ">
                          <el-space>
                            <el-form-item
                              :label-width="0"
                              :prop="`product[${$index}].warehouse[${g}].warehouse_id`"
                              required
                            >
                              <el-select v-model="wg.warehouse_id" size="small" placeholder="选择仓库" class="w-120px" clearable>
                                <el-option
                                  v-for="w in warehouseList"
                                  :key="w.id"
                                  :label="w.name"
                                  :value="w.id"
                                  :disabled="w.id !== wg.warehouse_id && row.warehouse.map(m => m.warehouse_id).includes(w.id)"
                                />
                              </el-select>
                            </el-form-item>

                            <el-form-item
                              v-for="(item, i) in wg.multi_unit"
                              :key="i"
                              :label-width="0"
                              :prop="`product[${$index}].warehouse[${g}].multi_unit[${i}].num`"
                              :required="wg.multi_unit.every(v => !Number(v.num))"
                            >
                              <el-input
                                v-model="item.num"
                                class="w-100px!"
                                placeholder="数量"
                                size="small"
                                oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                              >
                                <template #suffix><span class="text-#333!">{{ item.unit }}</span></template>
                              </el-input>
                            </el-form-item>
                            <div v-if="wg.multi_unit?.length > 1" class="flex-shrink-0 min-w-60px text-left">
                              = {{ totalUnit(wg.multi_unit) }}{{ wg.unit }}
                            </div>
                          </el-space>
                        </div>
                      </el-scrollbar>

                      <div class="flex-shrink-0">
                        <el-link v-if="g === 0" underline="never" type="primary" class="mx-10px" @click="addWg($index)"><span class="text-12px">新增</span></el-link>
                        <el-link underline="never" type="danger" :disabled="row.warehouse.length === 1" @click="removeWg($index, g)"><span class="text-12px">删除</span></el-link>
                      </div>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column
                  prop="price"
                  label="价格"
                  align="center"
                  :min-width="100"
                >
                  <template #default="{ row, $index }">
                    <el-form-item
                      :label-width="0"
                      :prop="`product[${$index}].price`"
                    >
                      <el-input
                        v-model="row.price"
                        placeholder="价格"
                        :input-style="{ textAlign: 'center' }"
                        oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,4})?.*$/,'$1')"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>

                <!-- <el-table-column prop="cost_price" label="调拨价" align="center" /> -->

                <el-table-column label="操作" width="100" align="center">
                  <template #default="{ $index }">
                    <el-link type="danger" underline="never" @click="removeProduct($index)">删除</el-link>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </ele-card>
        </el-form>
      </div>
    </el-scrollbar>
    <SelectProduct
      v-model="showProduct"
      editPrice
      :editNum="false"
      :selecteds="form.product"
      :where="{ supplier_id: form.supplier_id, su_id: form.su_id }"
      @done="selectProduct"
    />
  </ele-page>
</template>

<script setup>
import { listBanWarehouse, listSu, listSupplier } from '@/api/common'
import SelectProduct from '@/components/Common/SelectProduct/index.vue'

defineOptions({ name: 'OpenTransferEdit' })

const route = useRoute()
const router = useRouter()

const { routeTabKey, removePageTab, setPageTabTitle } = utils.usePageTab()

const formRef = ref(null)
const tableRef = ref(null)

const { totalUnit } = utils

const orderId = ref(0)

/** 是否是修改 */
const isUpdate = computed(() => orderId.value > 0)

const loading = ref(false)

const info = ref({ product: [] })
const suList = ref([])

const showProduct = ref(false)

const [supplierList] = utils.useGetList(listSupplier)

/** 表单数据 */
const [form, resetFields, assignFields] = utils.useFormData({
  id: undefined,
  supplier_id: '',
  su_id: '',
  order_date: '',
  contacts: '',
  phone: '',
  address: '',
  remark: '',
  product: [],
})

/** 表单验证规则 */
const rules = reactive({
  order_date: {
    required: true,
    message: '请选择单据日期',
    trigger: 'change',
  },
  supplier_id: {
    required: true,
    message: '请选择货主',
    trigger: 'change',
  },
  su_id: {
    required: true,
    message: '请选择开放平台用户',
    trigger: 'change',
  },
  product: {
    required: true,
    message: '请选择商品',
    type: 'array',
    trigger: 'change',
    min: 1,
  },
})

function goBack(path) {
  if (!path)
    path = '/open/transfer'
  removePageTab({ key: routeTabKey })
  router.push(path)
}

function getInfo() {
  utils.get('/apiTransfer/Info', { id: orderId.value }).then((res) => {
    info.value = res.data
    setPageTabTitle(`编辑要货单[${utils.ellipsisStr(res.data.order_sn, 0, 10)}]`)
    assignFields({
      ...form,
      ...res.data,
      enclosure: utils.encodeFiles(res.data.enclosure),
    })
  })
}

onMounted(() => {
  orderId.value = Number(route.params?.id)

  if (orderId.value) {
    getInfo()
  }
  else {
    setPageTabTitle('新增要货单')
  }
})

async function suChange(id) {
  if (!id) {
    return
  }
  const data = suList.value.find(v => v.id === id)
  if (!data) {
    return
  }
  data.contacts = data.contacts || data.consignee
  data.phone = data.phone || data.consignee_phone
  data.address = data.address || data.consignee_address

  if (!data.contacts && !data.phone && !data.address) {
    return
  }
  if (form.contacts || form.address || form.phone) {
    const [cancel] = await utils.awaitTo(utils.confirm(`是否使用${data.name}开放平台的默认收货地址`, '系统提示'))
    if (cancel)
      return
  }
  if (data.contacts)
    form.contacts = data.contacts
  if (data.phone)
    form.phone = data.phone
  if (data.address)
    form.address = data.address
}

const warehouseList = ref([])

watch([() => form.supplier_id, () => form.su_id], async (newVal, oldVal) => {
  if (oldVal?.[0] || oldVal?.[1]) {
    form.product = []
  }
  const newSupplierId = newVal[0]
  if (newSupplierId) {
    listBanWarehouse(newSupplierId).then((re) => {
      warehouseList.value = re.data
    })

    const res = await listSu(newSupplierId)
    suList.value = res.data
  }
  else {
    suList.value = []
  }
  if (form.su_id && !suList.value.some(v => v.id === form.su_id)) {
    form.su_id = ''
  }
}, {
  immediate: true,
})

function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true

    const formData = utils.cloneDeep(form)

    if (isUpdate.value) {
      formData.id = orderId.value
    }

    formData.product = formData.product.map((v) => {
      const warehouse = v.warehouse.map(d => ({
        warehouse_id: d.warehouse_id,
        multi_unit: d.multi_unit.map(t => ({ ...t, num: t.num || '' })),
        num: totalUnit(d.multi_unit),
      }))
      return {
        product_id: v.product_id,
        price: v.price,
        warehouse,
        num: warehouse.reduce((acc, cur) => utils.Big(acc).plus(cur.num).valueOf(), 0),
      }
    })

    // formData.num = formData.product.reduce((acc, cur) => utils.Big(acc).plus(cur.num).valueOf(), 0)

    utils.post('/apiTransfer/edit', formData)
      .then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          if (res.data.order_sn) {
            goBack(`/open/transfer/info/${res.data.order_sn}`)
          }
          else {
            goBack()
          }
        }
      })
      .finally(() => {
        loading.value = false
      })
  })
}

function selectProduct(data, row) {
  if (data.length) {
    data.forEach((v) => {
      // v.multi_unit = v.unit_list.map(d => ({ ...d, num: '' }))
      v.multi_unit = utils.totalUnit(v.multi_unit) > 0 ? v.multi_unit : v.unit_list.map(d => ({ ...d, num: '' }))
      v.warehouse = [{ warehouse_id: '', multi_unit: v.multi_unit }]
    })
    form.product.push(...data)
  }
  else if (row) {
    const index = form.product.findIndex(v => v.product_id === row.product_id)
    if (index === -1) {
      form.product.push(row)
    }
    else {
      form.product[index] = row
    }
  }
}

function removeProduct(index) {
  form.product.splice(index, 1)
}

function addWg(index) {
  if (!form.product[index].warehouse?.length) {
    form.product[index].warehouse = []
  }
  form.product[index].warehouse.push({
    warehouse_id: '',
    multi_unit: form.product[index].multi_unit,
  })
}

function removeWg(index, index2) {
  form.product[index].warehouse.splice(index2, 1)
}

function getSummaries({ columns, data }) {
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const keys = ['warehouse']
    if (keys.includes(column.property)) {
      sums[index] = data.reduce((acc, cur) => {
        let value = 0
        if (column.property === 'warehouse') {
          value = cur.warehouse.reduce((acc2, cur2) => utils.Big(acc2).plus(totalUnit(cur2.multi_unit)).valueOf(), 0)
        }
        else {
          value = cur[column.property]
        }
        return utils.Big(acc).plus(value).valueOf()
      }, 0)
    }
    else {
      sums[index] = ''
    }
  })

  return sums
}
</script>

<style lang="scss" scoped></style>
